package AlienArena::RCon::Response;
use POE;
use strict;
use warnings;

sub new {
    my $class = shift;
    my $console = shift;
    my $self = bless {}, $class;
    $self->{_console} = $console;
    return $self;
}

sub response_handler {
    my $self = $_[OBJECT]; # shift doesn't work here! it's a POE thing.
    my ($type, $ip, $port, $command, $id, $response) = @_[ARG0..ARG5];
    $self->{_from_address} = "$ip:$port";
    $self->{_command} = $command; 
    $self->{_id} = $id;
    $self->{_response} = $response;
    undef $self->{_error};
    $self->_set_state($response);
    if ($self->ok) { # do further parsing
	$self->_parse_response;
    }
    $self->console->kernel->yield('acknowledge_response');
}

sub _set_state {
    my $self = shift;
    my $response = shift;
    for ($response) {
	/^ERROR/ && do {
	    $self->{_error} = 1;
	    ($self->{_errmsg}) = $response =~ /ERROR:\s+(.*)/;
	    last;
	};
	do { # else
	    $self->{_error} = 0;
	};
    }
}

sub _parse_response {
    my $self = shift;
    local $_;
    $_ = $self->response;
    do {    # desired parsing 
	s/^print\s+//;
	/\sis\s/ && do {
	    s/\sis\s/\t/;
	    s/\"//g;
	};
	/SHUT UP/ && do {
	    s/SHUT UP.*DRUMS!\n//g;
	};
    };
    $self->{_parsed_response} = $_;
}

sub console { shift->{_console} }
sub id { shift->{_id} }
sub command { shift->{_command} }
sub as_text { shift->{_response} }
sub response { shift->{_response} }
sub parsed_response { shift->{_parsed_response} }
sub address { shift->{_from_address} }
sub error { shift->{_error} }
sub ok { !shift->{_error} }
sub errmsg { shift->{_errmsg} }

=head1 NAME

AlienArena::RCon::Response - Object containing parsed AA server response

=head1 SYNOPSIS

print $console->response->as_text;

=head1 DESCRIPTION

Parses server responses to Rcon commands as sent by L<AlienArena::Rcon::Console>.

=head1 METHODS

=head2 console

=head2 id

=head2 command

=head2 as_text

=head2 response

=head2 parsed_response

=head2 address

=head2 error

=head2 ok

=head2 errmsg

=head1 AUTHOR

Mark A. Jensen ( maj -at- fortinbras -dot- us )

=head1 SEE ALSO

L<AlienArena::RCon::Response>

=head1 LICENSE

=cut
    
1;
